<!-- eslint-disable -->
<template>
  <!-- 去除eslint，避免将驼峰的属性格式化为 -->
  <view
    :fileRandom="fileRandom"
    :change:fileRandom="chooseFile.fileRandomChange"
    :initRandom="initRandom"
    :change:initRandom="chooseFile.initRandomChange"
    :actionUrl="actionUrl"
    :change:actionUrl="chooseFile.actionUrlChange"
    :actionMethod="actionMethod"
    :change:actionMethod="chooseFile.actionMethodChange"
    :actionOption="actionOption"
    :change:actionOption="chooseFile.actionOptionChange"
    v-html="chooseFileHtml"
  />
</template>

<script>
export default {
  // 数据状态
  props: {
    accept: {
      type: String,
      default: 'video/*'
    },
    capture: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    action: {
      type: String,
      default: ''
    },
    method: {
      type: String,
      default: 'GET'
    },
    option: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      fileRandom: null,
      initRandom: null,
      actionUrl: null,
      actionMethod: null,
      actionOption: null,
      chooseFileHtml: '',
    }
  },

  // 响应事件 & 生命周期
  watch: {
    action(url) {
      this.actionUrl = url
    }
  },
  mounted() {
    this.initChooseFileHtml()
  },
  // 方法
  methods: {
    initChooseFileHtml() {
      this.chooseFileHtml = `<input
        style="display:none"
        type="file"
        accept="${this.accept}"
        ${this.capture ? `capture="${this.capture}"` : ''}
        ${this.multiple ? 'multiple' : ''}
        id="custom-choose-file">
      `

      // dom完成
      this.$nextTick(() => {
        this.initRandom = Math.random()
      })
    },
    fileUploadSuccess(e) {
      this.$emit('success', e)
    },
    fileUploadFail(e) {
      this.$emit('fail', e)
    },
    click() {
      this.fileRandom = Math.random()
    }
  }
}
</script>

<script module="chooseFile" lang="renderjs">
import TcVod from 'vod-js-sdk-v6'

export default {
  data() {
    return {
      fileInput: null,
      action: '' ,
      method: '',
      options: {},
    }
  },
  mounted() {
  },
  methods: {
    initRandomChange(e) {
      if (!e) return

      // 上传视频文件
      const fileEl = document.getElementById('custom-choose-file');
      this.fileInput = fileEl

      // 事件监听
      fileEl.addEventListener('change', (e) => {
        /**
         * TODO: 这里就已经拿到文件流了，处理自己的分片上传逻辑
         * let [file] = fileEl.files => file就是文件流
         * 可以通过自己的服务端接口进行上传 —— this.uploadAction(fileEl)
         * 可以使用vod-js-sdk-v6进行上传 —— https://cloud.tencent.com/document/product/266/9239
         */

        // 方式一：自定义的上传接口
        // this.uploadAction(fileEl).then(data => {
        //   this.$ownerInstance.callMethod('fileUploadSuccess', data)
        // }).catch(err => {
        //   this.$ownerInstance.callMethod('fileUploadFail', err)
        // })

        // 方式二：vod-js-sdk-v6 的分片上传
        this.sdkUpload(fileEl)
      })
    },

    /* 接收参数 - start */
    fileRandomChange(e) {
      if (!e) return
      this.fileInput.click()
    },
    actionUrl(url) {
      if (!url) return
      this.action = url
    },
    actionMethodChange(val) {
      if (!val) return
      this.method = val
    },
    actionOptionChange(val) {
      if (!val) return
      this.options = val || {}
    },
    /* 接收参数 - end */

    /**
     * 上传动作
     * @param {Object} fileEl 文件元素
     * @returns {Promise} 结果
     */
    uploadAction(fileEl) {
      let [file] = fileEl.files
      const formData = new FormData()
      formData.append('file', file)

      return new Promise((resolve, reject) => {
        fetch(this.action, {
          method: this.method || 'GET',
          body: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          ...this.options,
        })
        .then(response => response.json())
        .then(res => resolve(res))
        .catch((error) => reject(error))
      })
    },
    /**
     * vod-js-sdk-v6 的分片上传
     * @param {Object} fileEl 文件元素
     */
     sdkUpload(fileEl) {
      function getSignature() {
        return new Promise((resolve, reject) => {
          fetch('https://example.com/getSignature', {
            .then(response => response.json())
            .then(data => resolve(data.data))
        })
      }

      const tcVod = new TcVod({
        getSignature
      })

      let [fileObj] = fileEl.files

      const uploader = tcVod.upload({
        mediaFile: fileObj, // 媒体文件（视频或音频或图片），类型为 File
      })

      uploader.on('media_progress', (info) => {
        console.log('media_progress >>>', info.percent) // 进度，也可emit出去
      })

      uploader.done().then((doneResult) => {
        console.log("上传完成:", doneResult)
        this.$ownerInstance.callMethod('fileUploadSuccess', doneResult)
      }).catch((err) => {
        console.log("上传失败:", err)
        this.$ownerInstance.callMethod('fileUploadFail', err)
      })
    },
  }
}
</script>
